#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> res;
    void countSum(TreeNode* root, int target, vector<int> path, int sum)
    {

        if (root == nullptr) return;
        if (!root->left && !root->right && (sum + root->val) == target)
        {
            path.push_back(root->val);
            res.push_back(path);
        }
        else if (root->left || root->right)
        {
            path.push_back(root->val);
            if (root->left) countSum(root->left, target, path, sum + root->val);
            if (root->right) countSum(root->right, target, path, sum + root->val);
        }
    }
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        countSum(root, targetSum, vector<int>(), 0);
        return res;
    }
};